from google.appengine.api import memcache

import entities, wish as Wish, user, stats

MAX_ITEMS = 200

def listByUser(user_id):
    
    wishes = entities.Wish.all().filter("reserver_id = ", user_id).order("-created").fetch(MAX_ITEMS)
    
    return wishes

def add(wish_id, user_id):

    wish = Wish.wishById(wish_id)

    if wish == None or wish.owner_id == user_id or wish.reserver_id != None: return False

    wish.reserver_id = user_id
    
    wish.put()
    
    # invalidate cache
    mc_key = "ws/u/0/" + wish.owner_id
    data = memcache.delete(mc_key)
    
    user.increment(user_id, reservations = True)
    stats.increment(reservations = True)
    
    return wish

def remove(user_id, wish_id):
    
    wish = Wish.wishById(wish_id)
    
    if wish == None: return False
    
    if wish.reserver_id != user_id: return False

    wish.reserver_id = None
    wish.put()
    
    # invalidate cache
    mc_key = "ws/u/0/" + wish.owner_id
    data = memcache.delete(mc_key)
    
    user.decrement(user_id, reservations = True)

    return wish